/*
 * @Author: wangze@linkstec.com
 * @Date: 2022-01-13 09:25:20
 * @Function: Please Input Function
 */
// import Vue from 'vue'
// import Vuex from 'vuex'
import { Message } from 'element-ui';
import api from '@/api';
import DevMock from '@/config/devMock';
import { VINTEXFUND_USER_TOKEN } from '@/utils/constant';
import { isTrader, isAuditor, isOperator, isAnyRoles } from '@/config/permission';

// import VuexPersistence from 'vuex-persist';
Vue.use(Vuex);

// const vuexLocal = new VuexPersistence({
//   storage: window.localStorage
// });
const PREFIX = 'VINTEX_';
const USER_TOKEN = PREFIX + 'token';
const USER_INFO = PREFIX + 'userInfo';
const ORG_INFO = PREFIX + 'orgInfo';
const ROLE_ID = PREFIX + 'roleId';
const USER_CLIENT = PREFIX + 'client';

const REDIRECT_URL = process.env.VUE_APP_COSWEBURL;

const modulesFiles = require.context('./modules', true, /\.js$/);

const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/(.*\/)*([^.]+).*/ig, '$2');
  const value = modulesFiles(modulePath);
  modules[moduleName] = value.default;
  return modules;
}, {});

export default new Vuex.Store({
  modules,
  state: {
    userInfo: null,
    userClient: localStorage.getItem(USER_CLIENT) ? localStorage.getItem(USER_CLIENT) : '',
    contexInfo: null,
    avatar: require('@/assets/img/jiabin.jpg'),
    vintexfundToken: localStorage.getItem(VINTEXFUND_USER_TOKEN),
    token: localStorage.getItem(USER_TOKEN),
    globalUserInfo: JSON.parse(localStorage.getItem(USER_INFO) || '{}'),
    globalOrgInfo: JSON.parse(localStorage.getItem(ORG_INFO) || '{}'),
    isHidePageHeader: false // 是否隐藏头部
  },
  getters: {
    avatar: (state) => state.avatar,
    vintexfundToken: (state) => state.vintexfundToken,
    token: (state) => state.token,
    userInfo: (state) => state.userInfo,
    userClient: (state) => state.userClient,
    contexInfo: (state) => state.contexInfo,
    globalUserInfo: (state) => state.globalUserInfo,
    globalOrgInfo: (state) => state.globalOrgInfo,
    isHidePageHeader: (state) => state.isHidePageHeader,
    currentRole: (state) => state.permission.currentRole,
    roles: state => state.permission.roles,
    rolesName: state => state.permission.rolesName,
    permissionRouters: state => state.permission.routers,
    isTrader: state => isTrader(state.permission.rolesName),
    isAuditor: state => isAuditor(state.permission.rolesName),
    isOperator: state => isOperator(state.permission.rolesName),
    isTraderCurrent: state => isTrader(state.permission.currentRole),
    isAuditorCurrent: state => isAuditor(state.permission.currentRole),
    isOperatorCurrent: state => isOperator(state.permission.currentRole),
    isAnyRoles: state => isAnyRoles(state.permission.rolesName),
    endDateInfo: state => state.permission.endDateInfo,
    operatorInvestType: state => state.permission.operatorInvestType,
    traderFundType: state => state.permission.traderFundType,
    currentFundType: state => {
      return state.permission.currentRole === 'OPERATOR'
      ? state.permission.operatorInvestType
      : state.permission.traderFundType;
    }

  },
  mutations: {
    updateUserInfo (state, payload) {
      state.userInfo = payload;
    },
    updateContexInfo (state, payload) {
      state.contexInfo = payload;
    },
    clearLoginUserInfo (state) {
      state.vintexfundToken = null;
      state.token = null;
      state.userInfo = null;
      state.globalUserInfo = null;
      state.globalOrgInfo = null;
      state.userClient = '';

      localStorage.removeItem(ROLE_ID);
      localStorage.removeItem(VINTEXFUND_USER_TOKEN);
      localStorage.removeItem(USER_TOKEN);
      localStorage.removeItem(USER_INFO);
      localStorage.removeItem(ORG_INFO);
      localStorage.removeItem(USER_CLIENT);
    },
    updateVintexfundToken (state, payload) {
      state.vintexfundToken = payload.vintexfundToken;
    },
    updateShowCommitment (state, payload) {
      state.showCommitment = payload;
    },
    updatePathCommitment (state, payload) {
      state.pathCommitment = payload;
    },
    updateUserClient (state, payload) {
      state.userClient = payload;
      localStorage.setItem(USER_CLIENT, payload);
    },
    undateIsHidePageHeader (state, payload) {
      state.isHidePageHeader = payload;
    }
  },
  actions: {
    login ({ dispatch, commit }) {
      return new Promise((resolve, reject) => {
        const formData = {};
        let userCode;
        let instCode;
        let sign;
        let source;
        if (process.env.NODE_ENV === 'development') {
          // 开发环境，获取本地文件中的网址，模拟登录;
          // const { FAKE_URL } = DevMock;
          // userCode = GetRequest('userCode', FAKE_URL);
          // instCode = GetRequest('instCode', FAKE_URL);
          // sign = GetRequest('sign', FAKE_URL);
          // source = GetRequest('source', FAKE_URL);
          resolve();
        } else {
          userCode = GetRequest('userCode');
          instCode = GetRequest('instCode');
          sign = GetRequest('sign');
          source = GetRequest('source');
        }
        if (source == '1' || source == '2') {
          // 隐藏头部;
          commit('undateIsHidePageHeader', true);
        }
        if (userCode && instCode && sign && source) {
          commit('updateUserClient', source);

          // web端跳转 初始化
          api.auth.vintexWebLogin({ userCode, instCode, sign, source }, { showErrorNotify: 0 }).then(res => {
            const data = res.data;
            localStorage.setItem(VINTEXFUND_USER_TOKEN, data.vintexfundToken);
            commit('updateVintexfundToken', {
              vintexfundToken: data.vintexfundToken
            });
            const userInfo = _.cloneDeep(data.contextInfo);
            userInfo.roleIds = data.roleInfo;
            commit('updateUserInfo', userInfo);
            commit('updateContexInfo', data.contextInfo);
            resolve();
          }).catch(err => {
            dispatch('loginFail', err);
          });
          return;
        } else if (localStorage.getItem(VINTEXFUND_USER_TOKEN)) {
          formData.vintexfundToken = localStorage.getItem(VINTEXFUND_USER_TOKEN);
        } else {
          // setTimeout(() => {
          //   // localStorage.removeItem('VINTEX_token');
          //   localStorage.clear();
          //   window.location.href = REDIRECT_URL;
          // }, 1000);
          // return;
        }
        // return api.auth.init(formData, { showErrorNotify: 0 }).then((res) => {
        //   const data = res.data;
        //   if (data.shouldLogin) {
        //     return Promise.reject(new Error(errorMsgLogin));
        //   } else {
        //     localStorage.setItem(VINTEXFUND_USER_TOKEN, data.vintexfundToken);
        //     commit('updateVintexfundToken', {
        //       vintexfundToken: data.vintexfundToken
        //     });
        //     commit('updateUserInfo', data.userInfo);
        //     commit('updateContexInfo', data.contextInfo);
        //     resolve();
        //   }
        // }).catch((err) => {
        //   dispatch('loginFail', err);
        // });
      });
    },
    loginFail ({ commit }, err) {
      // 是否用户名密码登录
      const isPasswordLogin = JSON.parse(localStorage.getItem('VINTEX_login')); // 9：验证码登录，6或者6_V：密码登录
      localStorage.clear();
      if (['6', '6_V'].includes(isPasswordLogin)) {
        // 密码登录报错提示
        Message.error(err.retCodeMsg);
        setTimeout(() => {
          window.location.href = REDIRECT_URL;
        }, 2000);
      } else {
        // 非密码登录报错提示
        commit('globalDialog/show', {
          title: '登录失败',
          msg: '请使用用户名密码登录基金研究',
          errorMsg: err,
          redirect: REDIRECT_URL
        }, { root: true });
      }
    }
  }
  // plugins: [vuexLocal.plugin]
});

// 获取地址栏上的参数
function GetRequest (value, defaultUrl) {
  var url = defaultUrl || window.location.href;
  var object = {};
  if (url.indexOf('?') !== -1) {
      var str = url.split('?')[1];
      var strs = str.split('&');
      for (var i = 0; i < strs.length; i++) {
          object[strs[i].split('=')[0]] = strs[i].split('=')[1];
      }
  }
  return object[value];
}
